package com.WebMentorPro.system.controller;

import com.WebMentorPro.system.annotation.AuthCheck;
import com.WebMentorPro.system.common.BaseResponse;
import com.WebMentorPro.system.common.DeleteRequest;
import com.WebMentorPro.system.common.ErrorCode;
import com.WebMentorPro.system.common.ResultUtils;
import com.WebMentorPro.system.constant.UserConstant;
import com.WebMentorPro.system.exception.BusinessException;
import com.WebMentorPro.system.exception.ThrowUtils;
import com.WebMentorPro.system.model.dto.notification.NotificationAddRequest;
import com.WebMentorPro.system.model.dto.notification.NotificationQueryAdminRequest;
import com.WebMentorPro.system.model.dto.notification.NotificationQueryRequest;
import com.WebMentorPro.system.model.dto.notification.NotificationUpdateRequest;
import com.WebMentorPro.system.model.dto.user.UserQueryRequest;
import com.WebMentorPro.system.model.entity.Notification;
import com.WebMentorPro.system.model.entity.Teacher;
import com.WebMentorPro.system.model.entity.User;
import com.WebMentorPro.system.model.vo.ActivityVO;
import com.WebMentorPro.system.model.vo.LoginUserVO;
import com.WebMentorPro.system.model.vo.NotificationVO;
import com.WebMentorPro.system.model.vo.UserVO;
import com.WebMentorPro.system.service.NotificationService;
import com.WebMentorPro.system.service.TeacherService;
import com.WebMentorPro.system.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 通知公告接口
 *
 * @author bianxinyao
 */
@RestController
@RequestMapping("/notification")
@Slf4j
@Api(tags = {"通知公告接口"})
public class NotificationController {

    @Resource
    private UserService userService;

    @Resource
    private TeacherService teacherService;

    @Resource
    private NotificationService notificationService;

    // region 登录相关

    /**
     * 获取当前登录用户
     *
     * @param request
     * @return
     */
    @GetMapping("/get/login")
    public BaseResponse<LoginUserVO> getLoginUser(HttpServletRequest request) {
        User user = userService.getLoginUser(request);
        return ResultUtils.success(userService.getLoginUserVO(user));
    }

    /**
     * 获取当前登录异科导师
     *
     * @param request
     * @return
     */
    @GetMapping("/get/login/teacher")
    public BaseResponse<Teacher> getLoginTeacher(HttpServletRequest request) {
        Teacher teacher = teacherService.getLoginTeacher(request);
        return ResultUtils.success(teacher);
    }

    // endregion

    // region 增删改查

    /**
     * 创建管理员通知
     *
     * @param notificationAddRequest
     * @return
     */
    @PostMapping("/add/admin")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation(value = "创建管理员通知")
    public BaseResponse<Long> addAdminNotification(@RequestBody NotificationAddRequest notificationAddRequest) {
        if (notificationAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Notification notification = new Notification();
        BeanUtils.copyProperties(notificationAddRequest, notification);
        notification.setTeacherId(0);
        notification.setType("管理员通知");
        boolean result = notificationService.save(notification);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "创建管理员通知失败");
        return ResultUtils.success(notification.getId());
    }

    /**
     * 创建异科导师通知
     *
     * @param notificationAddRequest
     * @param notificationAddRequest
     * @return
     */
    @PostMapping("/add/teacher")
    @ApiOperation(value = "创建异科导师通知")
    public BaseResponse<Long> addTeacherNotification(@RequestBody NotificationAddRequest notificationAddRequest, HttpServletRequest request) {
        if (notificationAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Notification notification = new Notification();
        BeanUtils.copyProperties(notificationAddRequest, notification);
        notification.setTeacherId(Math.toIntExact(teacherService.getLoginTeacher(request).getId()));
        boolean result = notificationService.save(notification);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "创建异科导师通知失败");
        return ResultUtils.success(notification.getId());
    }

    /**
     * 删除通知（仅管理员）
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation(value = "删除通知（仅管理员）")
    public BaseResponse<Boolean> deleteNotification(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean result = notificationService.removeById(deleteRequest.getId());
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "删除通知失败");
        return ResultUtils.success(result);
    }

    /**
     * 更新通知
     *
     * @param notificationUpdateRequest
     * @param request
     * @return
     */
    @PostMapping("/update")
    @ApiOperation(value = "更新通知")
    public BaseResponse<Boolean> updateNotification(@RequestBody NotificationUpdateRequest notificationUpdateRequest, HttpServletRequest request) {
        if (notificationUpdateRequest == null || notificationUpdateRequest.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        Notification notification = new Notification();
        QueryWrapper<Notification> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", notificationUpdateRequest.getId());
        Notification one = notificationService.getOne(queryWrapper);
        if (one == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "通知不存在");
        }
        if (notificationUpdateRequest.getTitle() == null || notificationUpdateRequest.getTitle().equals("")) {
            notificationUpdateRequest.setTitle(one.getTitle());
        }
        if (notificationUpdateRequest.getContent() == null || notificationUpdateRequest.getContent().equals("")) {
            notificationUpdateRequest.setContent(one.getContent());
        }
        if (notificationUpdateRequest.getType() == null || notificationUpdateRequest.getType().equals("")) {
            notificationUpdateRequest.setType(one.getType());
        }
        BeanUtils.copyProperties(notificationUpdateRequest, notification);
        boolean result = notificationService.updateById(notification);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "更新通知失败");
        return ResultUtils.success(result);
    }

    /**
     * 分页获取全部通知
     *
     * @param notificationQueryRequest
     * @return
     */
    @PostMapping("/get/all/teacher")
    @ApiOperation(value = "分页获取全部异科导师通知")
    public BaseResponse<Page<NotificationVO>> listNotificationByPage(@RequestBody NotificationQueryRequest notificationQueryRequest) {
        long current = notificationQueryRequest.getCurrent() == 0 ? 1 : notificationQueryRequest.getCurrent();
        long size = notificationQueryRequest.getPageSize() == 0 ? 10 : notificationQueryRequest.getPageSize();

        Page<NotificationVO> pageParam = new Page<>(current, size);

        // 调用服务层方法获取分页数据
        Page<NotificationVO> notificationVOPage = notificationService.getQueryWrapper(pageParam, notificationQueryRequest);

        return ResultUtils.success(notificationVOPage);
    }

    /**
     * 分页获取全部管理员通知
     *
     * @param request
     * @return
     */
    @PostMapping("/get/all/admin")
    @ApiOperation(value = "分页获取全部管理员通知")
    public BaseResponse<Page<NotificationVO>> listNotificationVOByPage(@RequestBody NotificationQueryAdminRequest notificationQueryAdminRequest, HttpServletRequest request) {
        long current = notificationQueryAdminRequest.getCurrent() == 0 ? 1 : notificationQueryAdminRequest.getCurrent();
        long size = notificationQueryAdminRequest.getPageSize() == 0 ? 10 : notificationQueryAdminRequest.getPageSize();

        Page<NotificationVO> pageParam = new Page<>(current, size);

        // 调用服务层方法获取分页数据
        Page<NotificationVO> notificationVOPage = notificationService.getQueryByAdmin(pageParam, notificationQueryAdminRequest);

        return ResultUtils.success(notificationVOPage);
    }

    // endregion
}
